package cn.itsource.org.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.itsource.basic.other.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.RedisService;
import cn.itsource.basic.util.SendEmailService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.query.ShopQuery;
import cn.itsource.org.service.IShopService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop, ShopQuery> implements IShopService {

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Autowired
    RedisService redisService;

    @Autowired
    SendEmailService sendEmailService;

    @Override
    public PageList<Shop> queryPage(DepartmentQuery query) {
        return null;
    }

    @Override
    @Transactional
    public boolean storeHouse(Shop shop) {

        Example example = new Example(Shop.class);
        example.and().andEqualTo("name", shop.getName());

        List<Shop> list = mapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            throw new BusinessException("店铺名称已被注册!");
        }

        mapper.insertSelective(shop);

        Employee admin = shop.getAdmin();
        admin.init();
        employeeMapper.insertSelective(admin);

        shop.setAdminId(admin.getId());

        if (mapper.updateByPrimaryKeySelective(shop) > 0) {
            String key = IdUtil.fastSimpleUUID();
            redisService.setStringKeyAndValue(60, key, shop.getId().toString());
            sendEmailService.send("宠物医院激活", "http://localhost/shop/activation/" + key, admin.getEmail());
            return true;
        }
        return false;
    }

    @Override
    public boolean activation(String uuid) {
        //1.通过uuid作为key，从redis中获取数据
        String shopId = redisService.getKeyStringValue(uuid);
        //1.1如果获取不到，请联系管理员
        if (StringUtils.isBlank(shopId)) {
            throw new BusinessException("激活链接无效了，请联系管理员");
        }
        //2.激活店铺（修改state = 2）
        Shop shop = new Shop();
        shop.setId(Long.valueOf(shopId));
        shop.setState(2);
        return mapper.updateByPrimaryKeySelective(shop) > 0;
    }
}
